import loading from "/js/loading.js";
import { createEdit, saveButtonListener, Listener, getStudentSetTarget, initEditVal,createMonth,createDate } from './edit.js'
import { getMonthWeek } from '/js/util.js'
import {createShiftWrap} from './shift.js'
import {createCancelDialogWrap,createRegularCancelDialogWrap} from './cancelDialog.js'
import {createCourseWrapOneStep} from './orderClass.js'
let teacher_name = {}
let teacher_all = []
let teacher_state1 = []//已上课
let teacher_state0 = []//未上课
let teacher_state1_count = {},//统计已上课
    teacher_state0_count = {},//统计未上课
    is_success = false,//是否达到目标
    target = '',//目标
    count = 0//进度

export async function createClassWrap() {
    return new Promise(async (resolve) => {
        teacher_name = {}
        teacher_all = []
        teacher_state1 = []//已上课
        teacher_state0 = []//未上课
        teacher_state1_count = {},//统计已上课
            teacher_state0_count = {},//统计未上课
            is_success = false,//是否达到目标
            target = '',//目标
            count = 0//进度
        await getByCourse()
        let wrap = document.createElement('div')
        wrap.className = 'class-wrap'
        let top = WrapTop()
        let middle = WrapMiddle()
        let right = WrapRight()
        let bottom = WrapBottom()
        wrap.appendChild(top)
        top.appendChild(middle)
        top.appendChild(right)
        wrap.appendChild(bottom)
        $('.body')[0].appendChild(wrap)
        createMyClass()
        editListener()
        openDetail()
        createTargetList()
        buyCourse()
        setTimeout(() => {
            $('.class-wrap')[0].style.opacity = 1
            resolve('ok')
        })

        //转移课程
        $('.shift-course')[0].addEventListener('click',() => {
            $('#mask').show()
            $('#mask')[0].style.zIndex = 20
            createShiftWrap()
        })
    })
}



let getByCourse = async () => {
    let res = await ajax('stduent_query_teacher_curriculum', {}, 'post')
    teacher_name = {}
    teacher_all = []
    if (res?.data) {
        res.data.forEach(item => {
            if (!teacher_name[item.name]) {
                teacher_name[item.name] = [item]
                teacher_all.push(item)
            } else {
                teacher_name[item.name].push(item)
            }
        })
        let res2 = await ajax('select_mycourse_record', {
            cumonth: new Date().getMonth() === 0 ? '12' : new Date().getMonth(),
            cumonth1: new Date().getMonth() + 1
        }, 'post')
        res2.data = res2.data.filter(item => {
            return item.cumonth === new Date().getMonth() === 0 ? '12' : new Date().getMonth() || item.cumonth === new Date().getMonth() + 1
        })
        res2.data.forEach(item => {
            let week = getMonthWeek(item.cuyear, item.cumonth, item.cuday).getWeek
            if (item.cumonth === new Date().getMonth() + 1) {
                item.week = week + 4
            } else {
                item.week = week
            }
        })
        teacher_state1 = res2.data.filter(item => {
            return item.state === 1
        })
        teacher_state1.forEach(item => {
            if (item.cumonth === new Date().getMonth() + 1) {
                if (item.week === getMonthWeek(new Date().getFullYear(), new Date().getMonth() + 1, new Date().getDate()).getWeek) {
                    is_success = true
                }
            }

            if (!teacher_state1_count[`${item.week}`]) {
                teacher_state1_count[`${item.week}`] = [item]
            } else {
                teacher_state1_count[`${item.week}`].push(item)
            }
        })
        teacher_state0 = res2.data.filter(item => {
            return item.state === 0
        })
        teacher_state0.forEach(item => {
            if (!teacher_state0_count[`${item.week}`]) {
                teacher_state0_count[`${item.week}`] = [item]
            } else {
                teacher_state0_count[`${item.week}`].push(item)
            }
        })
    }

    let anticipation = await ajax('anticipation_query', {}, 'post')
    if (anticipation.code === 200) {
        count = Math.ceil(anticipation.data.money * 100)
        target = anticipation.data.level
    }


}

let WrapTop = function () {
    let div = document.createElement('div')
    div.className = 'animated fadeInUp'
    div.style.cssText = 'border-radius: 6px;;display:flex;align-items:stretch;width: 1200px;max-width:1200px;min-width:1200px;background: white;margin: 37px auto;'
    let left = is_success ? success() : fail()
    div.innerHTML = left
    return div
}

let WrapMiddle = function () {
    let cn_hash = {
        0: '一月',
        1: '二月',
        2: '三月',
        3: '四月',
        4: '五月',
        5: '六月',
        6: '七月',
        7: '八月',
        8: '九月',
        9: '十月',
        10: '十一月',
        11: '十二月',
    }
    let month = new Date().getMonth()
    let lastMonth, inMonth
    if (month === 0) {
        lastMonth = cn_hash[11]
        inMonth = cn_hash[month]
    } else {
        lastMonth = cn_hash[month - 1]
        inMonth = cn_hash[month]
    }


    let wrap = document.createElement('div')
    wrap.style.cssText = 'width:45%;margin-left:21px;align-items: center;display:flex;position: relative;'
    let div = `
        <div class='class-block3'>
            <div class='class-block4'>
                <span style='color:#FF8700 '>已完成</span>
                <div class='class-block5' style='border-bottom:2px solid #FF8700'>
                </div>
            </div>
            <div class='class-block4'>
                <span style='color:#3173FF '>已安排</span>
                <div class='class-block5' style='border-bottom:2px solid #3173FF'></div>
            </div>
            <div class='class-block4'>
                <span style='color:#7A7A7A '>未安排</span>
                <div class='class-block5' style='border-bottom:2px solid #7A7A7A'></div>
            </div>
        </div>
        <div style='left:5%;position:absolute;display:flex;flex-direction:row;border-bottom:2px solid #eee;height: 80%;width:90%;justify-content: space-between;'>
            <div class='class-block2'></div>
            <div class='class-block2'></div>
            <div class='class-block2'></div>
            <div class='class-block2'></div>
            <div class='class-block2'></div>
            <div class='class-block2'></div>
            <div class='class-block2'></div>
            <div class='class-block2' style='opacity:0'></div>
        </div>
        <div class='class-block8'>
            <div>${lastMonth}</div>
            <div></div>
            <div>${inMonth}</div>
            <div></div>
        </div>
    `
    wrap.innerHTML = div
    return wrap
}

let WrapRight = function () {

    let div = document.createElement('div')
    div.style.cssText = 'flex:1;display:flex;align-items:center;margin-left:30px'
    let top = `
        <div class='class-block9'>
            <div class='class-block10'>
                <div>进度</div>
                <div class='class-edit' style='color: #4580FE;cursor:pointer'>编辑</div>
            </div>
            <div style='margin-top:8px'>
                <span>预想目标</span>
                <span style='margin-left:14px'>${target}</span>
            </div>
            <div class="wrap">
                <div class="left">
                    <div class="progress" id="l"></div>
                </div>
                <div class="right">
                    <div style='transform:rotate(${-135 + (count * 18) / 5}deg)' class="progress" id="r"></div>
                </div>
                <div class='center'>${count}%</div>
            </div>
        </div> 
    `
    div.innerHTML = top

    return div
}

let WrapBottom = function () {
    let div = document.createElement('div')
    div.className = 'class-block13 animated fadeInUp'

    let top = () => {
        return `
            <div class='class-block14'>
                <div class='class-block15'>我的课程</div>
                <div class='class-block16' style='display:flex;align-items:center'>
                    <i class='iconfont icon-jiantou_zuoyouqiehuan' style='font-size:16px;color:#5686E9'></i>
                    <span class='shift-course' style='margin-left:7px;color:#5686E9;cursor:pointer'>转移课程</span>
                </div>
            </div>
            <div class='class-block17'>
                <div class='class-block18'>导师</div>
                <div class='class-block18'>已支付</div>
                <div class='class-block18'>每小时的价格</div>
                <div class='class-block18' style='margin-right:36px;text-align:right'>安排</div>
            </div>
            <div class='class-block19'>
                
            </div>
            
        `
    }

    div.innerHTML = top()
    return div
}

let createTargetList = () => {
    let leftToPx = {
        1 : '17px',
        2 : '78px',
        3 : '138px',
        4 : '199px',
        5 : '260px',
        6 : '322px',
        7 : '381px',
        8 : '439px'
    }
    let state1 = Object.keys(teacher_state1_count)
    let state0 = Object.keys(teacher_state0_count)
    state1.forEach((item, index) => {
        let left = leftToPx[teacher_state1_count[item][0].week]
        let div = document.createElement('div')
        div.className = 'class-block6'
        div.style.cssText = `position:absolute;left:${left}`
        div.innerHTML = `
            <div class='class-block7'>${teacher_state1_count[item].length}节</div>
        `
        $('.class-block5')[0].appendChild(div)
    })

    state0.forEach((item, index) => {
        let left = leftToPx[teacher_state0_count[item][0].week]
        let div = document.createElement('div')
        div.className = 'class-block6'
        div.style.cssText = `position:absolute;left:${left};border:4px solid #3173FF;`
        div.innerHTML = `
            <div class='class-block7 class-block7-new'>${teacher_state0_count[item].length}节</div>
        `
        $('.class-block5')[1].appendChild(div)
    })
}

let createMyClass = function () {
    let frag = document.createDocumentFragment()
    for (let i = 0; i < teacher_all.length; i++) {
        let block20 = document.createElement('div')
        let block23 = document.createElement('div')
        block20.className = 'class-block20'
        block23.className = 'class-block23'
        block23.id = `class-block${i}`
        block20.innerHTML = `
            <div class='class-block21' style='margin-left: 36px;'>
                <i class='iconfont icon-xiangxia' style='font-size:14px;color:#858585;transition:.4s;transform:rotate(360deg);cursor:pointer'></i>
                <img style='margin-left: 21px;border-radius:50%' src='${teacher_all[i].teacherimg}' width='29' height='29'/>
                <span style='margin-left:15px'>${teacher_all[i].name + '老师'}</span>
            </div>
            <div class='class-block21'>1hr</div>
            <div class='class-block21'>$ ${teacher_all[i].price}</div>
            <div class='class-block21'>
                <i class='iconfont icon-xinxi1' style='font-size:14px;color:#5686E9'></i>
                <span class='class-message' style='cursor:pointer;color:#5686E9;margin-left:5px'>信息</span>
                <div class='class-block22'>购买课程</div>
            </div>
        `
        block23.innerHTML = `
            <div class='class-block24'>
                <div style='margin-left:36px'>以前的课程</div>
                <div>状态</div>
                <div>时长</div>
                <div>已付款</div>
                <div>行动</div>
            </div>
        `
        teacher_name[teacher_all[i].name].forEach(item => {
            let time = new Date(`${item.cuyear}-${item.cumonth}-${item.cuday} ${item.timequantum}`).getTime()
            let div = document.createElement('div')
            div.className = 'class-block25'
            div.innerHTML = `
                <div style='margin-left:36px'>${item.cumonth}月${item.cuday}号${item.timequantum}点（常规课程）</div>
                <div>${item.state === 0 ? '未完成' : '已完成'}</div>
                <div>50分钟</div>
                <div>$${item.price}</div>
                <div>
                    <div style='${time > new Date().getTime() ? '' : 'display:none'}'  class='class-block26' data-curriculumid=${item.id}>取消常规课程</div>
                </div>
            `
            block23.appendChild(div)
        })
        frag.appendChild(block20)
        frag.appendChild(block23)
    }
    $('.class-block19')[0].appendChild(frag)

    if ($('.class-message')[0]) {
        $('.class-message')[0].addEventListener('click', () => {
            location.reload();
        })

        $('.class-block26').each(function(){
            $(this).on('click',async (e) => {
                $('#mask').show()
                $('#mask')[0].style.zIndex = '20'
                let {curriculumid} = e.target.dataset
                createCancelDialogWrap(curriculumid,$(e.target))
                
            })
        })
    }

}

let success = function () {
    return `
        <div style='display:flex;flex-direction:column'>
            <div style='margin-top:14px;margin-left:30px;font-size: 20px;font-family: Microsoft YaHei;font-weight: bold;color: #3C3C3C;'>
                你达到了本周的目标！
            </div>
            <div style='margin-top:10px;margin-left:30px;font-size:18px;color: #797979;'>
                坚持下去！
            </div>
            <img src='../../../static/success.png' width='339' height='256' style='margin-left:7px;margin-bottom:18px'/>
        </div>
    `
}

let fail = function () {
    return `
        <div style='display:flex;flex-direction:column'>
            <div style='margin-top:14px;margin-left:30px;font-size: 20px;font-family: Microsoft YaHei;font-weight: bold;color: #3C3C3C;'>
                你未达到了本周的目标
            </div>
            <div style='margin-top:10px;margin-left:30px;font-size:18px;color: #797979;'>
                加油啊！
            </div>
            <img src='../../../static/fail.png' width='198' height='183' style='margin-left:7px;margin-bottom:18px'/>
        </div>
    `
}

let openDetail = () => {
    $('.icon-xiangxia').each(function (index) {
        $(this).on('click', function (e) {
            if (e.target.style.transform === 'rotate(180deg)') {
                e.target.style.transform = 'rotate(360deg)'
                $(`#class-block${index}`).slideToggle("fast")
            } else {
                e.target.style.transform = 'rotate(180deg)'
                $(`#class-block${index}`).slideToggle("fast")
            }

        })
    })
}

let editListener = () => {
    $('.class-edit')[0].addEventListener('click', async () => {
        $('.class-wrap')[0] && $('.class-wrap')[0].remove()
        await getStudentSetTarget()
        let wrap = document.createElement('div')
        wrap.className = 'class-wrap'
        wrap.innerHTML = createEdit()
        $('.body')[0].appendChild(wrap)
        saveButtonListener()
        createMonth()
        createDate()
        Listener()
        initEditVal()
        setTimeout(() => {
            $('.class-wrap')[0].style.opacity = 1
        })
    })
}

let buyCourse = () => {
    $('.class-block22').each(function(){
        $(this).on('click',(e) => {
            $('.class-wrap')[0].remove()
            createCourseWrapOneStep()
        })
    })
}
